from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.support.wait import WebDriverWait
from mobitile.pages.login_page import *
from mobitile.pages.internal_page import *
from mobitile.pages.dash_page import *
from mobitile.pages.internal_admin_page import *
from mobitile.pages.create_user_page import *

__author__ = 'kzv'
class Application(object):

    def __init__(self, driver, base_url):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)
        self.base_url = base_url
        self.login_page = LoginPage(driver, base_url)
        self.internal_page = InternalPage(driver, base_url)
        self.internal_admin_page = InternalAdminPage(driver, base_url)
        self.dash_page = DashPage(driver, base_url)
        self.create_user_page = UserCreatePage(driver, base_url)

    def login(self, user):
        lp = self.login_page
        lp.username_field.clear()
        lp.username_field.send_keys(user.email)
        lp.password_field.clear()
        lp.password_field.send_keys(user.password)
        lp.submit_button.click()

    def logout(self):
        self.internal_page.logout_button.click()

    def add_user(self, user):
        self.dash_page.add_user_button.click()
        self.create_user_page.user_name_field.send_keys(user.username)
        self.create_user_page.user_email_field.send_keys(user.email)
        self.create_user_page.user_first_name_field.send_keys(user.firstname)
        self.create_user_page.user_last_field.send_keys(user.lastname)
        self.create_user_page.user_phone_field.send_keys(user.phone)
        self.create_user_page.user_create_and_list_button.click()

    def is_logged_in_client(self):
        driver = self.driver
        try:
            self.wait.until(presence_of_element_located((By.XPATH, ".//div[contains(.,'Logged in as ')]")))
            return True
        except WebDriverException:
            return False

    def is_not_logged(self):
        driver = self.driver
        try:
            self.wait.until(presence_of_element_located((By.ID, "username")))
            return True
        except WebDriverException:
            return False

    def is_logged_in_admin(self):
        driver = self.driver
        try:
            self.driver.wait.until(presence_of_element_located((By.XPATH, ".//alt[@alt]")))
        except WebDriverException:
            return False

    def go_to_home_page(self):
        driver = self.driver
        driver.get(self.base_url)

    def go_to_admin_page(self):
        driver = self.driver
        driver.get(self.base_url + "/admin")